<template>
  <div>
    <!-- 头部导航栏 -->
    <van-nav-bar title="修改信息" left-text="返回" left-arrow @click-left="$router.go(-1)" fixed />
    <van-cell v-for="item in list" :key="item" :title="item" />
    <van-back-top />
 
    <!-- 头像上传 -->
    <div class="head">
      <h1>修改头像</h1>
      <van-uploader v-model="fileList" :max-count="1"
        :after-read="(file) => onUpload(userStore.userInfo.id, file, '用户头像')" />
    </div>

    <!-- 信息修改 -->
    <div class="info">
      <van-cell-group @failed="onSubmit">
        <van-field v-model="editValue.username" label="名字" placeholder="非数字开头6-10位" />
        <van-field v-model="editValue.phone_number" label="手机号" placeholder="11位手机号" />
        <van-field v-model="editValue.password" label="密码" placeholder="1-6位数字或字母" />
        <van-field v-model="editValue.age" label="年龄" placeholder="合理的年龄" />
        <van-field v-model="editValue.idcardnumber" label="身份证号" placeholder="请输入身份证号" />
        <van-field v-model="editValue.licenseplate" label="车牌号" placeholder="请输入车牌号" />
      </van-cell-group>
     
      
      <van-button type="primary" @click="onSubmit(editValue)">修改</van-button>
    </div>
  </div>
  <van-tabbar route v-model="active" active-color="#cf2c2b">
      <van-tabbar-item replace to="/home/home" icon="home-o">首页</van-tabbar-item>
      <van-tabbar-item replace to="" icon="search">商城</van-tabbar-item>
      <van-tabbar-item replace to="" icon="aim">捕获</van-tabbar-item>
      <van-tabbar-item replace to="/user/userinfo" icon="user-o">我的</van-tabbar-item>
    </van-tabbar>
</template>

<script setup>
import { userApi } from '../../tools/api.js'
import { POST, UPLOAD } from "../../tools/fetch";
import { useRouter } from 'vue-router';
const router = useRouter();
import { ref } from 'vue';
import { useUserStore } from '../../tools/storage.js';
import { showSuccessToast, showToast } from 'vant';
const userStore = useUserStore();
const fileList = ref([]);
const editValue = ref({
  user_id: userStore.userInfo.user_id, 
  username: '',
  phone_number: '',
  age: '',
  password: '',
  avatar: '',
  idcardnumber: '', // 身份证号
  licenseplate: ''   // 车牌号
})
const editRules = ref([
  { key: 'username', pattern: /^[a-zA-Z\u4e00-\u9fa5][a-zA-Z0-9\u4e00-\u9fa5]{1,9}$/, message: '用户名格式错误' },
  // 手机号的正则
  { key: 'phone_number', pattern: /^1[3456789]\d{9}$/, message: '手机号格式错误' },
  // 密码的正则 
  { key: 'password', pattern: /^[\dA-Za-z]{3,7}$/, message: '密码号格式错误' },
  // 年龄正则
  { key: 'age', pattern: /^(1[8-9]|[2-8]\d|90)$/, message: '年龄有误' },
  // 头像正则
  // { key: 'head', pattern: /^\/upload/, message: '头像路径错误' }
]);
const onUpload = async (user_id, file, source) => {
  const formData = new FormData();
  formData.append('file', file.file);
  formData.append('source', source);
  // 发送请求
  const resResult = await UPLOAD(formData)
  editValue.value.avatar = resResult.key
  editValue.value.user_id = user_id;
  showSuccessToast('上传成功');
}
const onSubmit = async (values) => {
  const dataArr = ['username', 'phone_number', 'age', 'password', 'avatar', 'idcardnumber', 'licenseplate'];
  let filteredObject = {};

  dataArr.forEach(key => {
    if (values.hasOwnProperty(key) && values[key]) {
      filteredObject[key] = values[key];
    }
  });
  

  for (const key in filteredObject) {
    if (filteredObject.hasOwnProperty(key)) {
      const value = filteredObject[key];
      const rule = editRules.value.find(r => r.key === key);
      if (rule && !rule.pattern.test(value)) {
        showToast(rule.message); // 或者使用其他方式显示错误信息，如vant的showToast  
        return false
      }
    }
  }
  // console.log(filteredObject);

  const resResult = await POST({
    api: userApi.editinfo,
    data: filteredObject
  })
  console.log(resResult);
  if (resResult.data) {
    userStore.setUserInfo(resResult.data); 
} else {
    showToast('获取用户信息失败');
    return;
}
  userStore.setUserInfo(resResult.data);
  showSuccessToast('修改成功');
  setTimeout(() => {
    router.go(-1);
  }, 3000)

}

</script>

<style lang="less" scoped>
.head {
  margin-top: 18vh;
  margin-bottom: 5vh;
  width: 90%;                /* 设定宽度 */
  margin-left: auto;         /* 左边距自动 */
  margin-right: auto;        /* 右边距自动 */
  text-align: center;        /* 文本居中 */
}


h1 {
  font-size: 4vw;
}
.info {
  text-align: center;
}
.van-button {
    margin-top: 20px; 
    padding: 10px 20px; 
    background-color:blue; 
    color: white; 
    font-size: 16px; 
    border-radius: 15px; 
    width: 80%;
    display: inline-block;
}
</style>